import { Component } from './component.js';
import { NotificationManager } from '/src/util/notification/notification.js'

export class ComponentManager {
    static components = {};
    static instances = new Map();

    /**
     * 注册组件
     * @param {string} name - 组件名称
     * @param {Function} componentClass - 组件类
     */
    static register(name, componentClass, metadata = {}) {
        if (!name || !componentClass) {
            NotificationManager.error('组件名称和类不能为空');
            return;
        }

        if (!(componentClass.prototype instanceof Component)) {
            NotificationManager.error(`组件 ${name} 必须继承自 Component 类`);
            return;
        }

        if (this.components[name]) {
            NotificationManager.warning(`组件 ${name} 已经注册，将被覆盖`);
        }
        this.components[name] = { class: componentClass, ...metadata };
    }

    /**
     * 创建组件实例
     * @param {string} name - 组件名称
     * @param {jQuery|HTMLElement|string} container - 容器
     * @param {Object} options - 配置选项
     * @returns {Component|null} 返回创建的组件实例
     */
    static create(name, container, options = {}) {
        const componentInfo = this.components[name];
        if (!componentInfo) {
            throw new Error(`未找到组件: ${name}`);
        }

        const instance = new componentInfo.class(container, options);

        // 跟踪实例
        const instanceId = instance.cid;
        this.instances.set(instanceId, instance);

        // 添加销毁时的清理逻辑
        const originalDestroy = instance.destroy.bind(instance);
        instance.destroy = () => {
            originalDestroy();
            this.instances.delete(instanceId);
        };

        return instance;
    }

    /**
     * 获取所有已创建的组件实例
     * @returns {Map<string, Component>}
     */
    static getAll() {
        return this.components;
    }

    /**
     * 根据名称获取单个组件实例
     * @param {string} name
     * @returns {Component|null}
     */
    static get(name) {
        return this.components[name] || null;
    }

    /**
     * 销毁所有组件实例
     */
    static destroyAll() {
        this.instances.forEach(instance => {
            if (!instance.isDestroyed) {
                instance.destroy();
            }
        });
        this.instances.clear();
    }

    static findInstances(predicate) {
        return Array.from(this.instances.values()).filter(predicate);
    }
}

export default ComponentManager;